package com.shen.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.shen.service.OssService;
import com.shen.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    //上传头像到oss
    @Override
    public String upLoadAvatar(MultipartFile file) throws FileNotFoundException {


        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String uploadUrl = null;


        // Endpoint以杭州为例，其它Region请按实际情况填写。
        //String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
       // String accessKeyId = "<yourAccessKeyId>";
       // String accessKeySecret = "<yourAccessKeySecret>";

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传文件流。
        try {
            //获取上传文件流
            InputStream inputStream = file.getInputStream();
            String fileName=file.getOriginalFilename();
            String uuid= java.util.UUID.randomUUID().toString().replaceAll("-","");
            //replaceAll 替换-
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName=uuid+fileName;
            fileName=datePath+"/"+fileName;
            //inputStream = new FileInputStream("<yourlocalFile>");
            //参数 1，bucketname 2,上传到oss路径和名字，3，文件流
            //文件按照日期 分类 2019/12/12/12.jpg
            //获取当前日期 joda日期工具类


            ossClient.putObject(bucketName, fileName, inputStream);
            //手动拼接url
            String url=null;
            url = "http://" + bucketName + "." + endpoint + "/" + fileName;
            return  url;

        }
        catch (Exception e){

        }
            // 关闭OSSClient。
            ossClient.shutdown();
            return null;



    }

}
